using UnityEngine;

namespace Function.SkillEditor.Runtime
{
    [ExecuteInEditMode]
    public class BoxColliderDrawer : MonoBehaviour
    {
        public Color color = Color.white;
        private Material lineMat;
        private BoxCollider mCollider;

        void Start()
        {
            lineMat = new Material(Shader.Find("SCore/PureColor"));
            lineMat.SetColor("_Color", color);
            mCollider = GetComponent<BoxCollider>();
        }

        void OnRenderObject()
        {
            if (mCollider == null)
                return;

            Vector3[] points = new Vector3[8]
            {
                new Vector3(-mCollider.size.x / 2.0f, -mCollider.size.y / 2.0f, -mCollider.size.z / 2.0f),
                new Vector3(mCollider.size.x / 2.0f, -mCollider.size.y / 2.0f, -mCollider.size.z / 2.0f),
                new Vector3(mCollider.size.x / 2.0f, -mCollider.size.y / 2.0f, mCollider.size.z / 2.0f),
                new Vector3(-mCollider.size.x / 2.0f, -mCollider.size.y / 2.0f, mCollider.size.z / 2.0f),

                new Vector3(-mCollider.size.x / 2.0f, mCollider.size.y / 2.0f, -mCollider.size.z / 2.0f),
                new Vector3(mCollider.size.x / 2.0f, mCollider.size.y / 2.0f, -mCollider.size.z / 2.0f),
                new Vector3(mCollider.size.x / 2.0f, mCollider.size.y / 2.0f, mCollider.size.z / 2.0f),
                new Vector3(-mCollider.size.x / 2.0f, mCollider.size.y / 2.0f, mCollider.size.z / 2.0f)
            };

            for (int i = 0; i < points.Length; ++i)
            {
                points[i] += mCollider.center;
                points[i] = mCollider.transform.TransformPoint(points[i]);
            }

            lineMat.SetColor("_Color", color);

            DrawLine(points[0], points[1]);
            DrawLine(points[0], points[3]);
            DrawLine(points[0], points[4]);

            DrawLine(points[5], points[1]);
            DrawLine(points[5], points[4]);
            DrawLine(points[5], points[6]);

            DrawLine(points[2], points[1]);
            DrawLine(points[2], points[3]);
            DrawLine(points[2], points[6]);

            DrawLine(points[7], points[3]);
            DrawLine(points[7], points[4]);
            DrawLine(points[7], points[6]);
        }

        void DrawLine(Vector3 pointA, Vector3 pointB)
        {
            if (lineMat == null)
                return;

            GL.Begin(GL.LINES);
            lineMat.SetPass(0);
            GL.Color(new Color(color.r, color.g, color.b, color.a));
            GL.Vertex3(pointA.x, pointA.y, pointA.z);
            GL.Vertex3(pointB.x, pointB.y, pointB.z);
            GL.End();
        }
    }
}